package lium.lbs.lbsim.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.*;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.event.LoginStateChangeEvent;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lmlibrary.Constants;
import com.lmlibrary.R;
import lium.lbs.lbsim.OBaseActivity;
import lium.lbs.lbsim.base.BaseParamMap;
import com.lmlibrary.base.DemoCallback;
import com.lmlibrary.bean.ResponseBean;
import com.lmlibrary.event.ClearActivtyStackEvent;
import com.lmlibrary.event.LoginOutEvent;
import lium.lbs.lbsim.jgchat.activity.MainActivity;
import lium.lbs.lbsim.pay.weixinpay.WXPayActivity;
import lium.lbs.lbsim.utils.SpUtils;
import lium.lbs.lbsim.utils.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Response;
import com.lmlibrary.exception.MyException;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.utils.OkLogger;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import lium.lbs.lbsim.jchat.utils.DialogCreator;
import lium.lbs.lbsim.jchat.utils.FileHelper;
import lium.lbs.lbsim.jchat.utils.SharePreferenceManager;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public abstract class BaseActivity extends OBaseActivity implements View.OnClickListener {


    protected int mWidth;
    protected int mHeight;
    protected float mDensity;
    protected int mDensityDpi;

    protected FrameLayout rootContent;
    public CompositeDisposable mCompositeDisposable;
    public boolean fitsystemwindows = false;
    private Dialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        QMUIStatusBarHelper.translucent(this, getResources().getColor(R.color.colorPrimaryDark));
        QMUIStatusBarHelper.setStatusBarLightMode(this);

        if (fitsystemwindows) {
            setContentView(R.layout.lb_activity_base_fitsystemwindows_content);
        } else {
            setContentView(R.layout.lb_activity_base_content);
        }
        FrameLayout contentLayout = findViewById(R.id.content);
        if (getLayoutId() != 0) {
            contentLayout.addView(getLayoutInflater().inflate(getLayoutId(), null));
        }
        initView(savedInstanceState);
        getNetWorkData();
        JMessageClient.registerEventReceiver(this);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mDensity = dm.density;
        mDensityDpi = dm.densityDpi;
        mWidth = dm.widthPixels;
        mHeight = dm.heightPixels;
    }

    protected void setTitle(String title) {
        if (findViewById(R.id.center_text) != null) {
            TextView ceterTv = findViewById(R.id.center_text);
            ceterTv.setVisibility(View.VISIBLE);
            ceterTv.setText(title + "");
        }
    }

    /**
     * 标题+返回键
     *
     * @param title
     */
    protected void setTitleWithBack(String title) {
        setTitle(title);
        if (findViewById(R.id.left_img) != null) {
            findViewById(R.id.left_img).setVisibility(View.VISIBLE);
            findViewById(R.id.left_img).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    /**
     * 返回Activity 布局文件的id
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 在此方法中初始化ui
     */
    protected abstract void initView(Bundle savedInstanceState);

    /**
     * 在此方法中调用页面数据的方法
     */
    protected abstract void getNetWorkData();


    public void addOnClickListeners(@IdRes int... ids) {
        if (ids != null) {
            for (@IdRes int id : ids) {
                if (findViewById(id) != null) {
                    findViewById(id).setOnClickListener(this);
                }

            }
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onDestroy() {
        //注销消息接收
        JMessageClient.unRegisterEventReceiver(this);
        if (dialog != null) {
            dialog.dismiss();
        }
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        clearDisposable();
    }

    /**
     * 添加订阅
     */
    public void addDisposable(Disposable mDisposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(mDisposable);


    }

    /**
     * 取消所有订阅
     */
    public void clearDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }

    int time = 1;

    /**
     * 模拟假数据
     * 倒计时3秒
     */
    public void postFakeData(final DemoCallback demoCallBack) {
        Observable.interval(1, TimeUnit.SECONDS)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .take(time + 1)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        demoCallBack.onSuccess();
                    }
                })
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {

                    }
                });
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @Subscribe
    public void onEventMainThread(LoginOutEvent event) {
        finish();
    }

    @Subscribe
    public void onEventMainThread(ClearActivtyStackEvent event) {

        OkLogger.e("-----1event:" + event.className);
        OkLogger.e("-----2this :" + getClass().getName());
        if (!getClass().getName().equals(event.className)) {
            finish();
        }
    }

    public void onEventMainThread(LoginStateChangeEvent event) {
        final LoginStateChangeEvent.Reason reason = event.getReason();
        UserInfo myInfo = event.getMyInfo();
        if (myInfo != null) {
            String path;
            File avatar = myInfo.getAvatarFile();
            if (avatar != null && avatar.exists()) {
                path = avatar.getAbsolutePath();
            } else {
                path = FileHelper.getUserAvatarPath(myInfo.getUserName());
            }
            SharePreferenceManager.setCachedUsername(myInfo.getUserName());
            SharePreferenceManager.setCachedAvatarPath(path);
            JMessageClient.logout();
        }
        switch (reason) {
            case user_logout:
                View.OnClickListener listener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case lium.lbs.lbsim.R.id.jmui_cancel_btn:
                               Intent intent = new Intent(BaseActivity.this, lium.lbs.lbsim.activity.LoginActivity.class);
                                startActivity(intent);
                                dialog.dismiss();
                                break;
                            case lium.lbs.lbsim.R.id.jmui_commit_btn:
                                JMessageClient.login(SpUtils.getInstance().get(Constants.memberId, "").toString(), SpUtils.getInstance().get(Constants.phonepw, "").toString(), new BasicCallback() {
                                    @Override
                                    public void gotResult(int responseCode, String responseMessage) {
                                        if (responseCode == 0) {
                                            Intent intent = new Intent(BaseActivity.this, lium.lbs.lbsim.activity.MainActivity.class);
                                            startActivity(intent);
                                        }
                                    }
                                });
                                dialog.dismiss();
                                break;
                        }
                    }
                };
                dialog = DialogCreator.createLogoutStatusDialog(BaseActivity.this, "您的账号在其他设备上登录", listener);
                dialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;
            case user_password_change:
                Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
                startActivity(intent);
                break;
        }
    }
}
